#include "SudokuEnvironment.h"
#include "SudokuChromosomeFactory.h"
#include "Chromosome.h"

#include "parameters.h"

SudokuEnvironment::SudokuEnvironment(int _populationSize,
                                 SudokuData _sudokuData) :
                        AbstractEnvironment(_populationSize),
                        sudokuData(_sudokuData)//TODO !!! pointer!! no copy!!
{
    TRACE_FUNC_ENTRY

    //max fitness is sudoku size^2 * 3
    setBestFitness(sudokuData.getSize() * sudokuData.getSize() * 3);

    chromosomeFactory = new SudokuChromosomeFactory(sudokuData);
}

SudokuEnvironment::~SudokuEnvironment()
{
    TRACE_FUNC
}

void SudokuEnvironment::fitnessFunction(Chromosome& chrom)
{
    TRACE_FUNC_ENTRY
    double fitness = 0.0;

    int chromIndex = 0;

    //qDebug() << chrom.size() << " " << chrom;
    //qDebug() << "@" << sudokuData;

    //TODO do funkcji:
    SudokuData sudCpy(sudokuData);

    //fill sudoku with data from chromosome
    for(int i=0;i<sudCpy.getSize() * sudCpy.getSize();++i)
    {
        if(sudCpy.cellAt(i).getValue() == 0)
        {
            sudCpy[i].setValue(chrom.at(chromIndex).toInt(),Guess);
            chromIndex++;
        }
    }

    //qDebug() << sudCpy;

    fitness = sudCpy.countIndividuals();

    chrom.setFitness(fitness);
    TRACE_FUNC_EXIT
}

QString SudokuEnvironment::decodeChromosome(const Chromosome& chrom)
{
    QString str("TODO");
    int chromIndex = 0;
    SudokuData sudCpy(sudokuData);

    //fill sudoku with data from chromosome
    for(int i=0;i<sudCpy.getSize() * sudCpy.getSize();++i)
    {
        if(sudCpy.cellAt(i).getValue() == 0)
        {
            sudCpy[i].setValue(chrom.at(chromIndex).toInt(),Guess);
            chromIndex++;
        }
    }
    qDebug() << sudCpy;

    return str;
}
